package com.kly.cashmall.services;

import com.kly.cashmall.services.api.Api;
import com.kly.cashmall.services.gson.CustomGsonConverterFactory;
import com.kly.cashmall.services.interceptor.HeaderInterceptor;
import com.kly.cashmall.services.interceptor.LoggingInterceptor;
import com.kly.cashmall.services.interceptor.TokenInterceptor;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import retrofit2.CallAdapter;
import retrofit2.Converter;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

public class Network {
    private static Api api;
    private static Converter.Factory gsonConverterFactory = GsonConverterFactory.create();
    private static CallAdapter.Factory rxJavaCallAdapterFactory = RxJava2CallAdapterFactory
            .create();

    public static Api getApi() {
        if (api == null) {
            OkHttpClient.Builder builder = new OkHttpClient.Builder();
            builder.addInterceptor(new HeaderInterceptor());
            builder.addInterceptor(new TokenInterceptor());
//            if (BuildConfig.DEBUG) {
            builder.addInterceptor(new LoggingInterceptor());
//            }
            OkHttpClient okHttpClient = builder.connectTimeout(30, TimeUnit.SECONDS).
                    readTimeout(30, TimeUnit.SECONDS).
                    writeTimeout(30, TimeUnit.SECONDS).build();

            Retrofit retrofit = new Retrofit.Builder()
                    .client(okHttpClient)
                    .baseUrl(BaseRequest.baseUrl)
                    .addConverterFactory(CustomGsonConverterFactory.create())
                    .addCallAdapterFactory(rxJavaCallAdapterFactory)
                    .build();
            api = retrofit.create(Api.class);
        }
        return api;
    }

}
